package com.app.system.common;

import com.app.system.config.properties.SystemParamProperties;
import com.google.common.collect.Maps;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 密码加密
 * Created by wcf-pc on 2018/12/5.
 *
 * @author wcf-pc
 */
@Component
@SuppressWarnings("all")
public class EncipherPwd {

    @Resource
    private SystemParamProperties systemParamProperties;

    /**
     * 根据传入用户名、明文密码获取一个加密的密码、加密盐
     *
     * @param username
     * @param password
     * @return
     */
    public Map<String, String> getEncipherPwd(String username, String password) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        // 加密方式
        String hashAlgorithmName = systemParamProperties.getHashedCredentialsMatcherHashAlgorithmName();
        // 密码原值
        String crdentials = password;
        // 以账号+salt作为盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(username + salt);
        // 加密1024次
        int hashIterations = systemParamProperties.getHashedCredentialsMatcherHashIterations();
        // 加密结果
        Object result = new SimpleHash(hashAlgorithmName, crdentials, credentialsSalt, hashIterations);
        // 结果集
        Map<String, String> map = Maps.newLinkedHashMap();
        map.put("username", username);
        map.put("password", result + "");
        map.put("salt", salt);
        return map;
    }

    /**
     * 根据用户名，设置初始密码
     *
     * @param username
     * @return
     */
    public Map<String, String> getEncipherPwd(String username) {
        return this.getEncipherPwd(username, systemParamProperties.getInitPassword());
    }

    /**
     * 根据传入的信息，获得加密的密码
     *
     * @param username
     * @param password
     * @param salt
     * @return
     */
    public String getCredentialsPwd(String username, String password, String salt) {

        String hashAlgorithmName = systemParamProperties.getHashedCredentialsMatcherHashAlgorithmName();//加密方式

        ByteSource credentialsSalt = ByteSource.Util.bytes(username + salt);//以账号+salt作为盐值

        int hashIterations = systemParamProperties.getHashedCredentialsMatcherHashIterations();//加密1024次

        Object result = new SimpleHash(hashAlgorithmName, password, credentialsSalt, hashIterations);

        return String.valueOf(result);
    }
}
